define(['jquery', 'bootstrap', 'backend', 'table', 'form','template','litestoregoods'], function ($, undefined, Backend, Table, Form,Template,litestoregoods) {

    var Controller = {
        index: function () {
            $(".btn-add").data("area", ["1000px","800px"]);
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'litestore/litestoregoods/index',
                    add_url: 'litestore/litestoregoods/add',
                    edit_url: 'litestore/litestoregoods/edit',
                    del_url: 'litestore/litestoregoods/del',
                    multi_url: 'litestore/litestoregoods/multi',
                    import_url: 'litestore/litestoregoods/import',
                    table: 'litestore_goods',
                }
            });

            var table = $("#table");

            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='category_id']", form).addClass("selectpage").data("source", "litestore/litestorecategory/index").data("primaryKey", "id").data("field", "name").data("orderBy", "weigh desc");
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'goods_id',
                sortName: 'goods_sort',
                search: false,
                ///显示导出按钮
                showExport: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'goods_id', title: __('Goods_id')},
                        {field: 'goods_name', title: __('Goods_name'), operate: 'LIKE'},
                        {field: 'pro_no', title: __('Pro_no'), operate: 'LIKE'},
                        {field: 'name_p', title: __('CategoryName'),operate: false},
                        {field: 'category_id', visible:false,title: __('Category_id')},
                        {field: 'images', title: __('Image'),operate: false, formatter: Table.api.formatter.images},
                        {field: 'spec_type', title: __('Spec_type'), visible: false,searchList: {"10":__('Single specification'),"20":__('Multiple specifications')}, formatter: Table.api.formatter.normal},
                        {field: 'long', title: __('Long'), visible: false, operate: false},
                        {field: 'wide', title: __('Wide'), visible: false, operate: false},
                        {field: 'high', title: __('High'), visible: false, operate: false},
                        {field: 'weight', title: __('Weight'), visible: false, operate: false},
                        {field: 'sales_initial', title: __('Sales_initial'),visible: false,operate: false},
                        {field: 'sales_actual', title: __('Sales_actual'),visible: false,operate: false},
                        {field: 'grade', title: __('Grade'),visible: false,operate: false},
                        {field: 'flag', title: __('Flag'), searchList: {"hot":__('FlagHot'),"recommend":__('FlagRecommend')}, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        {field: 'goods_price', title: __('Goods_price'),operate: false},
                        {field: 'line_price', title: __('Line_price'),operate: false},
                        {field: 'cost_price', title: __('Cost_price'),operate: false},
                        {field: 'goods_sort', title: __('Goods_sort'),operate: false},
                        {field: 'starttime', title: __('On sale time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'endtime', title: __('Goods removed time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'goods_status', title: __('Goods_status'), searchList: {"10":__('On sale'),"20":__('Goods removed')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), visible: false,operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            table.on('load-success.bs.table',function(data){
               $(".btn-editone").data("area", ["1000px","800px"]);
            });

            // 导出
            $(document).on("click", ".btn-export", function () {

                // //获取搜索参数
                // var formdata = $("form.form-commonsearch").serialize();
                // host = window.location.host;
                // host2=window.location.protocol;
                //
                // Fast.api.ajax({
                //     url:'litestore/litestoregoods/export?' +formdata
                // }, function(msg){
                //     window.location.href=host2 + "//"+ host + msg;
                // }, function(){
                //     console.log('导出失败');
                // });

                var filter='{';
                var op='{';

                // 跳转
                var formdata = $("form.form-commonsearch").serialize();
                var data=formdata.split('&');
                var new_data = [];
                data.forEach(function(v){
                    let a= v.split('=');
                    new_data[a[0]] = a[1];
                })
                data.forEach(function(v){
                    let a= v.split('=');
                    var str = a[0];
                    if(str.indexOf("operate")==-1){
                        if(a[1]){
                            filter+='"'+[a[0]]+'":"'+a[1]+'",';
                            op+='"'+[a[0]]+'":"'+new_data[a[0]+'-operate']+'",';
                        }
                    }else{

                    }

                })
                if(filter.length > 2){
                    filter=filter.slice(0,-1);
                    op=op.slice(0,-1);
                }
                var url='litestoregoods/export?addtabs=1&sort=id&order=desc&offset=0&limit=18000&filter=';
                url += filter +'}&op='+ op+'}';
                window.open(url);

            });

        },
        add: function () {
            Form.api.bindevent($("form[role=form]"), function(data, ret){
                Fast.api.close(data);
                Toastr.success("商品提交成功");
            }, function(data, ret){
                Toastr.success("商品提交失败");
            }, function(success, error){
                //注意如果我们需要阻止表单，可以在此使用return false;即可
                //如果我们处理完成需要再次提交表单则可以使用submit提交,如下
                var form = this;
                if (form.size() === 0) {
                    Toastr.error("表单未初始化完成,无法提交");
                    return false;
                }
                var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                url = form.attr("action");
                url = url ? url : location.href;
                //修复当存在多选项元素时提交的BUG
                var params = {};
                var multipleList = $("[name$='[]']", form);
                if (multipleList.size() > 0) {
                    var postFields = form.serializeArray().map(function (obj) {
                        return $(obj).prop("name");
                    });
                    $.each(multipleList, function (i, j) {
                        if (postFields.indexOf($(this).prop("name")) < 0) {
                            params[$(this).prop("name")] = '';
                        }
                    });
                }
                var dataParam = {spec_many: specMany.getData()};
                Fast.api.ajax({
                    type: type,
                    url: url,
                    data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : '') + (Object.keys(dataParam).length > 0 ? '&' + $.param(dataParam) : ''),
                    dataType: 'json',
                    complete: function (xhr) {
                        var rr = JSON.parse(xhr.responseText);
                        if(rr.code == '0'){
                            Toastr.error(ret.mag);
                            return false;
                        }
                        var token = xhr.getResponseHeader('__token__');
                        if (token) {
                            $("input[name='__token__']", form).val(token);
                        }
                        //关闭弹窗
                        var index = parent.Layer.getFrameIndex(window.name);
                        var callback = parent.$("#layui-layer" + index).data("callback");
                        parent.Layer.close(index);
                        //刷新列表
                        parent.$("#table").bootstrapTable('refresh');
                    }
                }, function (data, ret) {
                    $('.form-group', form).removeClass('has-feedback has-success has-error');
                    if (data && typeof data === 'object') {
                        if (typeof data.token !== 'undefined') {
                            $("input[name='__token__']", form).val(data.token);
                        }
                        if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
                            data.callback.call(form, data);
                        }
                    }
                }, function (data, ret) {
                    if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
                        $("input[name='__token__']", form).val(data.token);
                    }
                });
                return false;
            });

            // 注册商品多规格组件
            var specMany = new GoodsSpec({
                container: '.goods-spec-many',
                OutForm:Form
            });

            // 切换单/多规格
            $('select[name="row[spec_type]"').change(function (e) {
                var $goodsSpecMany = $('.goods-spec-many')
                    , $goodsSpecSingle = $('.goods-spec-single');
                if (e.currentTarget.value === '10') {
                    $goodsSpecMany.hide() && $goodsSpecSingle.show();
                } else {
                    $goodsSpecMany.show() && $goodsSpecSingle.hide();
                }
            });


        },
        edit: function () {
            //Controller.api.bindevent();

            Form.api.bindevent($("form[role=form]"), function(data, ret){
                //Fast.api.close(data);
                Toastr.success("商品提交成功");
            }, function(data, ret){
                Toastr.success("商品提交失败");
            }, function(success, error){
                //注意如果我们需要阻止表单，可以在此使用return false;即可
                //如果我们处理完成需要再次提交表单则可以使用submit提交,如下
                var form = this;
                if (form.size() === 0) {
                    Toastr.error("表单未初始化完成,无法提交");
                    return false;
                }
                var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                url = form.attr("action");
                url = url ? url : location.href;
                //修复当存在多选项元素时提交的BUG
                var params = {};
                var multipleList = $("[name$='[]']", form);
                if (multipleList.size() > 0) {
                    var postFields = form.serializeArray().map(function (obj) {
                        return $(obj).prop("name");
                    });
                    $.each(multipleList, function (i, j) {
                        if (postFields.indexOf($(this).prop("name")) < 0) {
                            params[$(this).prop("name")] = '';
                        }
                    });
                }
                var dataParam = {spec_many: specMany.getData()};
                Fast.api.ajax({
                    type: type,
                    url: url,
                    data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : '') + (Object.keys(dataParam).length > 0 ? '&' + $.param(dataParam) : ''),
                    dataType: 'json',
                    complete: function (xhr) {
                        var token = xhr.getResponseHeader('__token__');
                        if (token) {
                            $("input[name='__token__']", form).val(token);
                        }
                        //关闭弹窗
                        var index = parent.Layer.getFrameIndex(window.name);
                        var callback = parent.$("#layui-layer" + index).data("callback");
                        parent.Layer.close(index);
                        //刷新列表
                        parent.$("#table").bootstrapTable('refresh');
                    }
                }, function (data, ret) {
                    $('.form-group', form).removeClass('has-feedback has-success has-error');
                    if (data && typeof data === 'object') {
                        if (typeof data.token !== 'undefined') {
                            $("input[name='__token__']", form).val(data.token);
                        }
                        if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
                            data.callback.call(form, data);
                        }
                    }
                }, function (data, ret) {
                    if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
                        $("input[name='__token__']", form).val(data.token);
                    }
                });
                return false;
            });
            // 注册商品多规格组件
            var specMany = new GoodsSpec({
                container: '.goods-spec-many',
                OutForm:Form
            }, from_specData);

            // 切换单/多规格
            $('select[name="row[spec_type]"').change(function (e) {
                var $goodsSpecMany = $('.goods-spec-many')
                    , $goodsSpecSingle = $('.goods-spec-single');
                if (e.currentTarget.value === '10') {
                    $goodsSpecMany.hide() && $goodsSpecSingle.show();
                } else {
                    $goodsSpecMany.show() && $goodsSpecSingle.hide();
                }
            });
        },
        select: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'litestore/litestoregoods/select',
                }
            });

            var table = $("#table");

            var goods_ids_str= Backend.api.query('element_id');//已选中id
            var goods_ids=goods_ids_str.split(",");
            // 复选框的处理事件---start---
            var idArr = [];
            var results = [];
            var multiple = Backend.api.query('multiple');
            multiple = multiple == 'true' ? true : false;
            table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function (e, row) {
                if (e.type == 'check' || e.type == 'uncheck') {
                    row = [row];
                } else {
                    idArr = [];
                    results = [];
                }

                $.each(row, function (i, j) {
                    if (e.type.indexOf("uncheck") > -1) {
                        var index = idArr.indexOf(j.goods_id);
                        if (index > -1) {
                            idArr.splice(index, 1);
                            results.splice(index, 1);
                        }
                    } else {
                        idArr.indexOf(j.goods_id) == -1 && idArr.push(j.goods_id) && results.push(j);
                    }
                });
            });
            // 复选框的处理事件---end---
            // 点击工具栏的选择按钮触发事件
            $(document).on("click", ".btn-choose-multi", function () {
                Fast.api.close({goods_id: idArr.join(","), multiple: multiple, rows: results}); // 回传数据给Fast.api.open的callback
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'goods_id',
                sortName: 'goods_id',
                search: false,
                showToggle: false,
                showExport: false,
                maintainSelected: true,
                columns: [
                    [
                        {checkbox: multiple, visible: multiple, operate: false,formatter:function(value, row, index){
                                if (goods_ids.some((item) => item == row.goods_id)){
                                    return {disabled: true};
                                }
                            }},
                        {field: 'goods_id', title: __('GoodsId')},
                        {field: 'goods_name', title: __('Goods_name'),operate: 'LIKE'},
                        {field: 'pro_no', title: __('Pro_no'), operate: 'LIKE'},
                        {field: 'images', title: __('Image'),operate: false, formatter: Table.api.formatter.images},
                        {field: 'goods_price', title: __('Goods_price'),operate: false},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        select_sku: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'litestore/litestoregoods/select_sku',
                }
            });

            var table = $("#table");

            var goods_ids_str= Backend.api.query('element_id');//已选中id
            var goods_ids=goods_ids_str.split(",");
            // 复选框的处理事件---start---
            var idArr = [];
            var results = [];
            var multiple = Backend.api.query('multiple');
            multiple = multiple == 'true' ? true : false;
            table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function (e, row) {
                if (e.type == 'check' || e.type == 'uncheck') {
                    row = [row];
                } else {
                    idArr = [];
                    results = [];
                }

                $.each(row, function (i, j) {
                    if (e.type.indexOf("uncheck") > -1) {
                        var index = idArr.indexOf(j.goods_id);
                        if (index > -1) {
                            idArr.splice(index, 1);
                            results.splice(index, 1);
                        }
                    } else {
                        idArr.indexOf(j.goods_id) == -1 && idArr.push(j.goods_id) && results.push(j);
                    }
                });
            });
            // 复选框的处理事件---end---
            // 点击工具栏的选择按钮触发事件
            $(document).on("click", ".btn-choose-multi", function () {
                Fast.api.close({goods_id: idArr.join(","), multiple: multiple, rows: results}); // 回传数据给Fast.api.open的callback
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'goods_id',
                sortName: 'goods_id',
                search: false,
                showToggle: false,
                showExport: false,
                maintainSelected: true,
                columns: [
                    [
                        {checkbox: multiple, visible: multiple, operate: false,formatter:function(value, row, index){
                                if (goods_ids.some((item) => item == row.goods_spec_id)){
                                    return {disabled: true};
                                }
                            }},
                        {field: 'goods_id', title: __('GoodsId')},
                        {field: 'goods.goods_name', title: __('Goods_name'),operate: 'LIKE'},
                        {field: 'goods.pro_no', title: __('Pro_no'), operate: 'LIKE'},
                        {field: 'images', title: __('Image'),operate: false, formatter: Table.api.formatter.images},
                        {field: 'sku_text', title: __('Spec_type'),operate: false},
                        {field: 'goods_price', title: __('Goods_price'),operate: false},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});